﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Data;
using ExcelLoader;
using Microsoft.Win32;
using OfficeOpenXml;
using MDSCommon;

namespace MDSAdministration
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //When the datagrid header checkbox is created you can not reference it. So using CheckBox Initialized to get reference
        public CheckBox cbxDataAttributesAll;
        public CheckBox cbxDataAttributeGroupsAll;
        public CheckBox cbxDataAttributeGroupDetailsAll;
        public CheckBox cbxdgExcelUploadAdvLoadFilesAll;

        private MDSManager mdsManager = new MDSManager();
        public List<mdsModel> models;

        private ServerMDSDetails ServerA = new ServerMDSDetails();
        private ServerMDSDetails ServerB = new ServerMDSDetails();

        private CompareModel modelA { get; set; }
        private CompareModel modelB { get; set; }

        //public static CompareModel CurrentModel { get; set; }


        private LinearGradientBrush lgbLightGreenVerticalGradient;
        private LinearGradientBrush lgbLightPurpleVerticalGradient;
        private LinearGradientBrush lgbLightOrangeVerticalGradient;
        private LinearGradientBrush lgbLightRedVerticalGradient;

        private Brush hPinkGrey;
        private SolidColorBrush sbLavinder;
        private SolidColorBrush sbLightGrey;

        private ServerDirection _sDirection;

        public ServerDirection sDirection
        {
            get { return _sDirection; }
            set { _sDirection = value; }
        }

        //have to have cs exposed as a property for the binding to work.
        public CheckStates cs = new CheckStates();
        public ExcelUploadAdvanced eua;
        public ExcelUpload euSimple;
        public ExcelHelper ehMapper;

        public CheckStates cStates
        {
            get { return cs; }
            set { cs = value; }
        }


        public MainWindow()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            this.DataContext = this;
            lgbLightGreenVerticalGradient = new LinearGradientBrush();
            lgbLightGreenVerticalGradient.StartPoint = new Point(0.5, 0);
            lgbLightGreenVerticalGradient.EndPoint = new Point(0.5, 1);
            lgbLightGreenVerticalGradient.GradientStops.Add(new GradientStop(Colors.LightGreen, 0.0));
            lgbLightGreenVerticalGradient.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1.0));

            lgbLightRedVerticalGradient = new LinearGradientBrush();
            lgbLightRedVerticalGradient.StartPoint = new Point(0.5, 0);
            lgbLightRedVerticalGradient.EndPoint = new Point(0.5, 1);
            lgbLightRedVerticalGradient.GradientStops.Add(new GradientStop(Colors.Red, 0.0));
            lgbLightRedVerticalGradient.GradientStops.Add(new GradientStop(Colors.DarkRed, 1.0));

            lgbLightPurpleVerticalGradient = new LinearGradientBrush();
            lgbLightPurpleVerticalGradient.StartPoint = new Point(0.5, 0);
            lgbLightPurpleVerticalGradient.EndPoint = new Point(0.5, 1);
            lgbLightPurpleVerticalGradient.GradientStops.Add(new GradientStop(Colors.LavenderBlush, 0.0));
            lgbLightPurpleVerticalGradient.GradientStops.Add(new GradientStop(Colors.Orchid, 1.0));

            lgbLightOrangeVerticalGradient = new LinearGradientBrush();
            lgbLightOrangeVerticalGradient.StartPoint = new Point(0.5, 0);
            lgbLightOrangeVerticalGradient.EndPoint = new Point(0.5, 1);
            lgbLightOrangeVerticalGradient.GradientStops.Add(new GradientStop(Colors.LemonChiffon, 0.0));
            lgbLightOrangeVerticalGradient.GradientStops.Add(new GradientStop(Colors.DarkOrange, 1.0));

            hPinkGrey = HatchBrush.PinkGrey;
            sbLavinder = new SolidColorBrush(Color.FromArgb(70, 220, 120, 218));
            sbLightGrey = new SolidColorBrush(Color.FromArgb(25, 169, 169, 169));

            models = new List<mdsModel>();

            sDirection = ServerDirection.ServerB;

            //Tab Excel Upload
            cbxExcelUploadSimSheets.DisplayMemberPath = "Name";
            cbxExcelUploadSimSheets.SelectedValuePath = "SheetName";

            //Tab Excel Upload Advanced Mapping
            cbxExcelUploadAdvMappingSheets.DisplayMemberPath = "Name";
            cbxExcelUploadAdvMappingSheets.SelectedValuePath = "SheetName";

            eua = new ExcelUploadAdvanced(this);
            euSimple = new ExcelUpload();
            ehMapper = new ExcelHelper();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            changeDirection(false);

            lblObjectAttributeDetails.Content = "";
            lblAttributeDetails.Content = "";
            lblAttributes.Content = "";
        }

        /*
        private OperationResult BuildTreeModel()
        {
            OperationResult or = new OperationResult();

            Metadata md = null;
            md = mdsManager.GetMetaData(new International(), ref or, null, null, null, MDAction.ModelsOnly);

            try
            {

                foreach (var m in md.Models)
                {
                    mdsModel mm = new mdsModel() { model = m, Name = m.Identifier.Name, Id = m.Identifier };

                    mm.Versions = new List<mdsVersion>();
                    var versions = mdsManager.GetMetaData(new International(), ref or, m.Identifier, null, null, MDAction.VersionsOnly);

                    foreach (var v in versions.Versions)
                    {
                        mdsVersion mv = new mdsVersion() { Id = v.Identifier, Name = v.Identifier.Name, version = v, model = mm };

                        mv.Entities = new List<mdsEntity>();
                        var entities = mdsManager.GetMetaData(new International(), ref or, m.Identifier, v.Identifier, null, MDAction.EntitiesOnly);

                        foreach (var en in entities.Entities)
                        {
                            mdsEntity men = new mdsEntity() { entity = en, Name = en.Identifier.Name, Id = en.Identifier, IsFlat = en.IsFlat, IsBase = en.IsBase, IsSystem = en.IsSystem, version = mv };

                            men.Attributes = new List<mdsAttribute>();
                            var attributes = mdsManager.GetMetaData(new International(), ref or, m.Identifier, v.Identifier, en.Identifier, MDAction.AttributesOnly);

                            foreach (var a in attributes.Attributes)
                            {
                                mdsAttribute ma = new mdsAttribute() { attribute = a, Name = a.Identifier.Name, MemberType = a.Identifier.MemberType.ToString(), AttributeType = a.AttributeType.ToString(), DataType = a.DataType.ToString() };
                                if (a.AttributeType == MDSAdministration.mdsService.AttributeType.Domain)
                                {
                                    ma.DomainEntityName = a.DomainEntityId.Name;
                                }
                                men.Attributes.Add(ma);
                            }
                            mv.Entities.Add(men);
                        }
                        mm.Versions.Add(mv);
                    }

                    models.Add(mm);
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.Message);
            }

            trvModel.ItemsSource = models;
            return or;
        }
         private void populateGrid(mdsModel model, mdsVersion version, mdsEntity entity)
        {
            var members = new List<mdsType>();
            var result = mdsManager.GetMembers(model.Id, version.Id, entity.Id, "");

            dgEdit.Columns.Clear();

            foreach (var att in entity.Attributes)
            {
                if (att.MemberType == Constants.ATTRIBUTE_TYPE_LEAF)
                {
                    var textColumn = new DataGridTextColumn();
                    textColumn.Header = att.Description;
                    textColumn.Binding = new Binding(att.Description);
                    dgEdit.Columns.Add(textColumn);

                }
            }

            foreach (var m in result.Members)
            {
                var member = mdsCreator.FactoryMethod(entity.Name);

                Type type = member.GetType();

                var prop = type.GetProperty("Name");
                prop.SetValue(member, m.MemberId.Name, null);

                prop = type.GetProperty("Code");
                prop.SetValue(member, m.MemberId.Code, null);

                foreach (var a in m.Attributes)
                {
                    prop = type.GetProperty(a.Identifier.Name);
                    if(a.Value.GetType().ToString() == "MSDAdministration.mdsService.MemberIdentifier")
                    {
                        prop.SetValue(member, ((MDSAdministration.mdsService.MemberIdentifier)a.Value).Code, null);
                    }
                    else if (a.Type == AttributeValueType.Domain)
                    {
                        prop.SetValue(member, DisplayDomainAttributeValue(a), null);
                    }
                    else
                    {
                        prop.SetValue(member, a.Value, null);
                    }

                }
                members.Add(member);
            }

            dgEdit.ItemsSource = members;
        } 
          private void trvModel_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            pgDetails.Instance = e.NewValue;
            if (e.NewValue.GetType().Name == "mdsEntity")
            {
                var entity = (mdsEntity)e.NewValue;

                populateGrid(entity.version.model, entity.version, entity);
            }
        }

        #region Edit Tab
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            var model = models.Find(m => m.Name == "TestModel");
            var version = model.Versions.Find(v => v.Name == "VERSION_1");
            var entity = version.Entities.Find(en => en.Name == "Product");

            populateGrid(model, version, entity);
        }

        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems != null && e.AddedItems.Count > 0)
            {
                StackPanelBuilder spb = new StackPanelBuilder();
                spb.BuildStackPanel(e.AddedItems[0], this.splFields);
            }
        }
        #endregion
         private void btnEditConnect_Click(object sender, RoutedEventArgs e)
        {
            BuildTreeModel();
        } 
          
        */

        #region Connection and Change Direction

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            var cw = new ConnectWindow();

            cw.ServerA = ServerA;
            cw.ServerB = ServerB;

            ShowConnectDialog(cw);
        }

        private void btnDataHelperRefresh_Click(object sender, RoutedEventArgs e)
        {
            using (new WaitCursor())
            {
                CompareModel();
            }
        }

        private void btnDCDataHelperRefresh_Click(object sender, RoutedEventArgs e)
        {
            CompareData();
        }

        private void ShowConnectDialog(ConnectWindow cw)
        {
            bool? dialogResult = cw.ShowDialog();

            if (dialogResult == true)
            {
                ServerA = cw.ServerA;
                ServerB = cw.ServerB;

                if (sDirection == ServerDirection.ServerA)
                {
                    txtExcelUploadAdvDatabaseName.Text = ServerA.Database + "Load";
                }
                else
                {
                    txtExcelUploadAdvDatabaseName.Text = ServerB.Database + "Load";
                }

                btnDataHelperRefresh.IsEnabled = true;
                btnDataHelperDeploy.IsEnabled = true;

                btnDCDataHelperRefresh.IsEnabled = true;
                btnDCDataHelperDeploy.IsEnabled = true;

                using (new WaitCursor())
                {
                    getModelDetails();

                    setConnectionLabels();

                    ClearAllDataGrids();

                    //need to do this when uploading data to staginging entities and have to handle
                    //special case were the lenght is less than "~null~" when nulling a string.
                    CompareModel();

                    if (this.tbiModelDataCompare.IsSelected)
                    {
                        CompareData();
                    }
                    else if (this.tbiExcelUpload.IsSelected)
                    {
                        ExcelUploadConnectionChange();
                    }

                    SetCurrentModel();
                }
            }
        }

        private void SetCurrentModel()
        {
            ResourceWrapper r = new ResourceWrapper();
            r.CurrentModel = getServerDirectionModel();
        }

        private void ExcelUploadConnectionChange()
        {
            setConnectionLabels();
            CompareModel();
        }

        private void imgDirection_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            changeDirection(true);
        }

        private void changeDirection(bool change)
        {
            try
            {
                if (change)
                {
                    if (sDirection == ServerDirection.ServerA)
                    {
                        sDirection = ServerDirection.ServerB;
                    }
                    else
                    {
                        sDirection = ServerDirection.ServerA;
                    }
                    SetCurrentModel();

                }
                if (sDirection == ServerDirection.ServerB)
                {
                    //Schema Images
                    imgSCServerA.Source = new BitmapImage(new Uri(@"/images/database_grey.png", UriKind.Relative));
                    imgSCServerB.Source = new BitmapImage(new Uri(@"/images/database_green.png", UriKind.Relative));
                    imgSCDirection.Source = new BitmapImage(new Uri(@"/images/Left_green.png", UriKind.Relative));
                    //Data Images
                    imgDCServerA.Source = new BitmapImage(new Uri(@"/images/database_grey.png", UriKind.Relative));
                    imgDCServerB.Source = new BitmapImage(new Uri(@"/images/database_green.png", UriKind.Relative));
                    imgDCDirection.Source = new BitmapImage(new Uri(@"/images/Left_green.png", UriKind.Relative));
                    //Excel Upload Images
                    imgExcelUploadServerA.Source =
                        new BitmapImage(new Uri(@"/images/database_grey.png", UriKind.Relative));
                    imgExcelUploadServerB.Source =
                        new BitmapImage(new Uri(@"/images/database_green.png", UriKind.Relative));
                    imgExcelUploadDirection.Source =
                        new BitmapImage(new Uri(@"/images/Left_green.png", UriKind.Relative));

                    txtExcelUploadAdvDatabaseName.Text = ServerB.Database + "Load";

                }
                else
                {
                    //Schema Images
                    imgSCServerA.Source = new BitmapImage(new Uri(@"/images/database_violet.png", UriKind.Relative));
                    imgSCServerB.Source = new BitmapImage(new Uri(@"/images/database_grey.png", UriKind.Relative));
                    imgSCDirection.Source = new BitmapImage(new Uri(@"/images/Right_violet.png", UriKind.Relative));
                    //Data Images
                    imgDCServerA.Source = new BitmapImage(new Uri(@"/images/database_violet.png", UriKind.Relative));
                    imgDCServerB.Source = new BitmapImage(new Uri(@"/images/database_grey.png", UriKind.Relative));
                    imgDCDirection.Source = new BitmapImage(new Uri(@"/images/Right_violet.png", UriKind.Relative));
                    //Data Images
                    imgExcelUploadServerA.Source =
                        new BitmapImage(new Uri(@"/images/database_violet.png", UriKind.Relative));
                    imgExcelUploadServerB.Source =
                        new BitmapImage(new Uri(@"/images/database_grey.png", UriKind.Relative));
                    imgExcelUploadDirection.Source =
                        new BitmapImage(new Uri(@"/images/Right_violet.png", UriKind.Relative));

                    txtExcelUploadAdvDatabaseName.Text = ServerA.Database + "Load";
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void setConnectionLabels()
        {
            tbSCServerA.Text = "SERVER A: " + ServerA.ServerName +
                               " DATABASE: " + ServerA.Database +
                               " MODEL: " + ServerA.Model +
                               " VERSION: " + ServerA.ModelVersion +
                               " MDS VERSION: " + modelA.System.Version +
                               " MDS SCHEMAVERSION: " + modelA.System.SchemaVersion;

            tbSCServerB.Text = "SERVER B: " + ServerB.ServerName +
                               " DATABASE: " + ServerB.Database +
                               " MODEL: " + ServerB.Model +
                               " VERSION: " + ServerB.ModelVersion +
                               " MDS VERSION: " + modelB.System.Version +
                               " MDS SCHEMAVERSION: " + modelB.System.SchemaVersion;

            tbDCServerA.Text = tbSCServerA.Text;
            tbDCServerB.Text = tbSCServerB.Text;

            tbExcelUploadServerA.Text = tbSCServerA.Text;
            tbExcelUploadServerB.Text = tbSCServerB.Text;
        }

        #endregion

    
        private void EntitySelected(ComparedObject co)
        {
            
            switch (co.locationType)
            {
                case ObjectStatus.ServerA:
                    {
                        dgDataAttributes.DataContext = BusinessHelper.buildServerACompareAttributes(co, modelA);
                        dgDataAttributeGroups.DataContext = BusinessHelper.buildServerACompareAttributeGroups(co, modelA);
                        dgDataMdsObjectAttribute.DataContext = BusinessHelper.populateComparedEntityA(co, modelA);
                    }
                    break;
                case ObjectStatus.ServerB:
                    {
                        dgDataAttributes.DataContext = BusinessHelper.buildServerBCompareAttributes(co, modelB);
                        dgDataAttributeGroups.DataContext = BusinessHelper.buildServerBCompareAttributeGroups(co, modelB);
                        dgDataMdsObjectAttribute.DataContext = BusinessHelper.populateComparedEntityB(co, modelB);
                    }
                    break;
                case ObjectStatus.Same:
                case ObjectStatus.Rename:
                case ObjectStatus.Different:
                    {
                        dgDataAttributes.DataContext = BusinessHelper.buildServerSameDifferntRenameCompareAttributes(co, modelA, modelB, cStates);
                        dgDataAttributeGroups.DataContext = BusinessHelper.buildServerSameDifferntRenameCompareAttributeGroups(co, modelA, modelB, cStates);
                        dgDataMdsObjectAttribute.DataContext = BusinessHelper.populateComparedEntity(co, modelA, modelB);
                    }
                    break;
            }

            lblAttributes.Content = "Attributes - " + WpfHelper.SetLableAccessKey(co.ObjectName);

            lblAttributeGroup.Content = "Attribute Group - " + WpfHelper.SetLableAccessKey(co.ObjectName);

        }

        public CompareModel getServerDirectionModel()
        {
            return BusinessHelper.getServerDirectionModel(sDirection, modelA, modelB);
        }
        public ServerMDSDetails getServer()
        {
            if (sDirection == ServerDirection.ServerB)
            {
                return ServerB;
            }
            else
            {
                return ServerA;
            }
        }

        private string DisplayDomainAttributeValue(mdsService.Attribute a)
        {
            string name = "";
            if (!String.IsNullOrEmpty(((MDSAdministration.mdsService.MemberIdentifier)a.Value).Name.ToString()))
            {
                name = ((MDSAdministration.mdsService.MemberIdentifier)a.Value).Name.ToString();
            }

            return "{" + ((MDSAdministration.mdsService.MemberIdentifier)a.Value).Code.ToString() + "} " + name;
        }

        private void btnCodeBuild_Click(object sender, RoutedEventArgs e)
        {
            var cb = new CodeBuilder();
            txbCodeView.Text = cb.Build(models);
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {

        }

        private void ClearAllDataGrids()
        {
            //Schema Compare
            dgServerA.DataContext = null;
            dgServerB.DataContext = null;
            dgDataMdsObject.DataContext = null;
            dgDataMdsObjectAttribute.DataContext = null;

            ClearAttributesData();


            //Data Compare
            dgDataCompHelper.DataContext = null;
            dgDataCompareEntities.DataContext = null;
            DataCompareClearPanel();
        }
        public void getModelDetails()
        {
            DataSet dsA = DataHelper.GetMdsSystemDetails(ServerA);
            DataSet dsB = DataHelper.GetMdsSystemDetails(ServerB);

            modelA = new CompareModel();
            BusinessHelper.buildModelSytem(modelA, dsA, ServerA);

            modelB = new CompareModel();
            BusinessHelper.buildModelSytem(modelB, dsB, ServerB);
        }

        //public void buildModelSytem(CompareModel m, DataSet ds, ServerMDSDetails server)
        //{
        //    m.System = new CompareSystem
        //                   {
        //                       Name = ds.Tables[0].Rows[0][Constants.SYSTEM_PRODUCTNAME].ToString(),
        //                       RegistrationKey = ds.Tables[0].Rows[0][Constants.SYSTEM_PRODUCTREGISTRATIONKEY].ToString(),
        //                       SchemaVersion = ds.Tables[0].Rows[0][Constants.SYSTEM_SCHEMAVERSION].ToString(),
        //                       Version = ds.Tables[0].Rows[0][Constants.SYSTEM_PRODUCTVERSION].ToString()
        //                   };

        //    server.schemaVersion = modelA.System;
        //}



        private void CompareModel()
        {
            DataSet dsA = DataHelper.GetDataModelDetails(ServerA);
            if (dsA.Tables.Count > 0)
            {
                dgServerA.DataContext = dsA.Tables[0];
            }
            DataSet dsB = DataHelper.GetDataModelDetails(ServerB);
            if (dsB.Tables.Count > 0)
            {
                dgServerB.DataContext = dsB.Tables[0];
            }

            try
            {
                BusinessHelper.buildModel(dsA, modelA);
                BusinessHelper.buildModel(dsB, modelB);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK,
                    MessageBoxImage.Error);
                Console.WriteLine(ex.ToString());
            }



            var compResult = BusinessHelper.CompareModels(modelA, modelB, cStates, ServerA, ServerB);

            List<ComparedObject> co = new List<ComparedObject>(compResult.Values);
            var collection = new ListCollectionView(co);
            collection.CustomSort = new SortMDSGroups();
            collection.GroupDescriptions.Add(new PropertyGroupDescription("Location"));

            dgDataMdsObject.DataContext = collection;
        }

        private void dgDataMdsObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems != null && e.AddedItems.Count > 0 && e.AddedItems[0].GetType().FullName == Constants.MDSADMINISTRATION_COMPAREDOBJECT)
            {
                var co = (ComparedObject)e.AddedItems[0];

                ClearAttributesData();
                ClearAttributeGroupsData();
                ClearAttributeGroupDetailsData();

                DataGridColumnHeader header = WpfHelper.GetColumnHeader(0, dgDataAttributes);

                if (header != null)
                {
                    CheckBox tb = header.Template.FindName("HeaderCheckBox", header) as CheckBox;
                    if (tb != null)
                    {
                        tb.IsChecked = false;
                    }
                }

                switch (co.ObjectType)
                {
                    case Constants.OBJECT_TYPE_ENTITY:
                        EntitySelected(co);
                        tbcCompareSchemaAttributes.Visibility = Visibility.Visible;
                        break;
                    case "View":
                        ViewSelected(co);
                        tbcCompareSchemaAttributes.Visibility = Visibility.Hidden;
                        break;
                }
            }
        }

        private void ClearAttributesData()
        {
            //Set to null so that column header doesn't fire and change selected entity attributes to false;
            dgDataAttributes.DataContext = null;
            dgDataAttribute.DataContext = null;

            lblAttributes.Content = "";
        }
        private void ClearAttributeGroupsData()
        {
            //Set to null so that column header doesn't fire and change selected entity attributes to false;
            dgDataAttributeGroups.DataContext = null;
            dgDataAttributeGroupProperties.DataContext = null;

            lblAttributeGroup.Content = "";
        }
        private void ClearAttributeGroupDetailsData()
        {
            //Set to null so that column header doesn't fire and change selected entity attributes to false;
            dgDataAttributeGroupDetails.DataContext = null;
            dgDataAttributeGroupDetailProperties.DataContext = null;

            lblAttributeGroupDetail.Content = "";
        }

        private void ViewSelected(ComparedObject co)
        {
            switch (co.locationType)
            {
                case ObjectStatus.ServerA:
                    dgDataMdsObjectAttribute.DataContext = BusinessHelper.populateComparedViewA(co, modelA);
                    break;
                case ObjectStatus.ServerB:
                    dgDataMdsObjectAttribute.DataContext = BusinessHelper.populateComparedViewB(co, modelB);
                    break;
                case ObjectStatus.Same:
                case ObjectStatus.Different:
                case ObjectStatus.Rename:
                    dgDataMdsObjectAttribute.DataContext = BusinessHelper.populateComparedView(co, modelA, modelB);
                    break;
            }
            lblObjectAttributeDetails.Content = "View Details";
        }



        private void dgDataAttributes_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            ComparedAttributes RowDataContaxt = e.Row.DataContext as ComparedAttributes;
            if (RowDataContaxt != null)
            {
                switch (RowDataContaxt.Status)
                {
                    case ObjectStatus.Delete:
                        {
                            e.Row.Background = lgbLightRedVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Missing:
                        {
                            e.Row.Background = lgbLightPurpleVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Different:
                        {
                            e.Row.Background = lgbLightGreenVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Rename:
                        {
                            e.Row.Background = lgbLightOrangeVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Same:
                        {
                            e.Row.Background = System.Windows.Media.Brushes.White;
                        }
                        break;
                }
            }
        }

        private void dgDataAttribute_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            CompareObjectResultColour(sender, e);
        }



        private void dgDataAttributes_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            if (e.Column != null && e.Column.Header != null && e.Column.Header.ToString() == "SortOrder" && e.Row.Item.GetType().FullName == "MDSAdministration.ComparedAttributes")
            {
                var att = BusinessHelper.getCompareAttribute(((ComparedAttributes)e.Row.Item), ServerDirection.ServerA, modelA, modelB);
                if (att.IsSystem)
                {
                    e.Cancel = true;
                }
            }
        }
        #region Header CheckBoxes

        private void HeadCheck(object sender, RoutedEventArgs e, bool IsChecked, DataGrid dg)
        {
            if (dg.Items.SourceCollection != null)
            {
                foreach (object r in dg.Items.SourceCollection)
                {
                    var cs = (ComparedSortBase)r;
                    cs.Checked = IsChecked;
                    
                }
                dg.Items.Refresh();
            }
        }

        private void dgDataAttributes_Header_CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            HeadCheck(sender, e, true, dgDataAttributes);
        }

        private void dgDataAttributes_Header_CheckBox_UnChecked(object sender, RoutedEventArgs e)
        {
            HeadCheck(sender, e, false, dgDataAttributes);
        }

        private void dgDataAttributeGroups_Header_CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            HeadCheck(sender, e, true, dgDataAttributeGroups);
        }
        private void dgDataAttributeGroups_Header_CheckBox_UnChecked(object sender, RoutedEventArgs e)
        {
            HeadCheck(sender, e, false, dgDataAttributeGroups);
        }

        private void dgDataAttributeGroupDetails_Header_CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            HeadCheck(sender, e, true, dgDataAttributeGroupDetails);
        }
        private void dgDataAttributeGroupDetails_Header_CheckBox_UnChecked(object sender, RoutedEventArgs e)
        {
            HeadCheck(sender, e, false, dgDataAttributeGroupDetails);
        }

        private void ExcelUploadAdvancedLoadFileColumnHeaderStyle_CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            eua.LoadFileHeadCheck(sender, e, true);
        }

        private void ExcelUploadAdvancedLoadFileColumnHeaderStyle_CheckBox_UnChecked(object sender, RoutedEventArgs e)
        {
            eua.LoadFileHeadCheck(sender, e, false);
        }
        #endregion
        

        #region Data Compare
        private void dgDataCompareEntities_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 && e.AddedItems[0].GetType().FullName == Constants.MDSADMINISTRATION_ENTITYDATACOMPREDETAILS)
            {
                var ed = (EntityDataCompreDetails)e.AddedItems[0];
                SelectionChangedEntityCompare(ed);
            }
        }

        private void SelectionChangedEntityCompare(EntityDataCompreDetails ed)
        {
            if (ed.Match || !ed.Processed)
            {
                buildEntityCompare(ed);
            }
            else
            {
                MessageBox.Show("The entity attributes do not match.", "Mismatch", MessageBoxButton.OK,
                                MessageBoxImage.Warning);
            }
        }

        private void dgScroller_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            //TODO: how to fix scroller
        }


        private void btnDCDataHelperDeploy_Click(object sender, RoutedEventArgs e)
        {
            DeploymentBuilder db = new DeploymentBuilder();
            db.CurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

            db.Server = getServer();

            if (cs.ComparePushAllCodeName == false)
            {
                getSelectedMembers(db);
            }
            else
            {
                var entities = dgDataCompareEntities.ItemsSource;
                if (entities != null)
                {
                    DataSet ds = null;
                    foreach (EntityDataCompreDetails entity in entities)
                    {
                        if (entity.Processed == true)
                        {
                            var aem = new ActionEntityMember();

                            if (sDirection == ServerDirection.ServerB)
                            {
                                ds = EntityData.GetEntityCodeNameData(entity.EntityMUIDA, ServerA);
                                aem.EntityStagingTableName = entity.StagingBaseB;
                            }
                            else if (sDirection == ServerDirection.ServerA)
                            {
                                ds = EntityData.GetEntityCodeNameData(entity.EntityMUIDB, ServerB);
                                aem.EntityStagingTableName = entity.StagingBaseA;
                            }


                            aem.EntityName = entity.Name;

                            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                            {
                                foreach (DataRowView drv in ds.Tables[0].DefaultView)
                                {
                                    var am = new ActionMember();

                                    am.lMemberValue.Add(new MemberValue()
                                    {
                                        CodeValue = drv[Constants.MDSADMINISTRATION_CODE].ToString(),
                                        MemberName = Constants.MDSADMINISTRATION_CODE,
                                        ValueSource = drv[Constants.MDSADMINISTRATION_CODE].ToString(),
                                        Attribute =
                                            BusinessHelper.getServerDirectionModel(sDirection, modelA, modelB).Entities[
                                                CompareEntity.getEntityKey(aem.EntityName)].Attributes[
                                                    CompareAttribute.getAttributeKey(Constants.MDSADMINISTRATION_CODE,
                                                        Constants.MEMBER_TYPE_LEAF)]
                                    });

                                    am.lMemberValue.Add(new MemberValue()
                                    {
                                        CodeValue = drv[Constants.MDSADMINISTRATION_CODE].ToString(),
                                        MemberName = Constants.MDSADMINISTRATION_NAME,
                                        ValueSource = drv[Constants.MDSADMINISTRATION_NAME].ToString(),
                                        dataType = MDSDataTypes.String,
                                        Attribute =
                                            BusinessHelper.getServerDirectionModel(sDirection, modelA, modelB).Entities[
                                                CompareEntity.getEntityKey(aem.EntityName)].Attributes[
                                                    CompareAttribute.getAttributeKey(Constants.MDSADMINISTRATION_NAME,
                                                        Constants.MEMBER_TYPE_LEAF)]
                                    });

                                    aem.LActionMembers.Add(am);
                                }
                            }
                            db.LActionEntityMembers.Add(aem);
                        }

                    }
                }
            }

            var dlg = new DeploymentWindow();
            dlg.db = db;
            dlg.ShowDialog();
        }

        private void getSelectedMembers(DeploymentBuilder db)
        {
            if (dgDataCompareEntities.SelectedItem == null)
                return;

            List<EntityColumn> lSelectedColumns = new List<EntityColumn>();
            foreach (var col in gPanel.Children)
            {
                if (col.GetType().FullName == Constants.MDSADMINISTRATION_COLUMNCOMPARE)
                {
                    if (((ColumnCompare)col).ColumnHeaderName != Constants.MDSADMINISTRATION_HASH && ((ColumnCompare)col).ColumnHeaderName != Constants.MDSADMINISTRATION_CODE)
                    {
                        if (((ColumnCompare)col).IsChecked)
                        {
                            lSelectedColumns.Add(new EntityColumn { Name = ((ColumnCompare)col).ColumnHeaderName, isDomainEntity = ((ColumnCompare)col).IsDomainEntity, dataType = ((ColumnCompare)col).DataType, isStagingAttribute = false});
                        }
                    }
                }
            }

            var aem = new ActionEntityMember();

            if (sDirection == ServerDirection.ServerB)
            {
                aem.EntityStagingTableName = ((EntityDataCompreDetails)dgDataCompareEntities.SelectedItem).StagingBaseB;
            }
            else if (sDirection == ServerDirection.ServerA)
            {
                aem.EntityStagingTableName = ((EntityDataCompreDetails)dgDataCompareEntities.SelectedItem).StagingBaseA;

            }

            aem.EntityName = ((EntityDataCompreDetails)dgDataCompareEntities.SelectedItem).Name;

            foreach (DataRowView drv in dgDataCompHelper.ItemsSource)
            {
                if (drv["IsChecked"] != DBNull.Value && Convert.ToBoolean(drv["IsChecked"]) == true)
                {
                    bool bSame = drv[Constants.MDSADMINISTRATION_SERVA + Constants.MDSADMINISTRATION_HASHCODE] != DBNull.Value &&
                                 drv[Constants.MDSADMINISTRATION_SERVB + Constants.MDSADMINISTRATION_HASHCODE] != DBNull.Value &&
                                 drv[Constants.MDSADMINISTRATION_SERVA + Constants.MDSADMINISTRATION_HASHCODE].ToString() ==
                                 drv[Constants.MDSADMINISTRATION_SERVB + Constants.MDSADMINISTRATION_HASHCODE].ToString();


                    switch (((ComboBoxItem)cbxMDCViewType.SelectedValue).Content.ToString())
                    {
                        case Constants.DATA_COMPARE_FILTER_SAME:
                            {
                                if (bSame == false)
                                {
                                    continue;
                                }
                            }
                            break;
                        case Constants.DATA_COMPARE_FILTER_DIFFERENT:
                            {
                                if (bSame == true)
                                {
                                    continue;
                                }
                            }
                            break;
                    }

                    var am = new ActionMember();

                    am.lMemberValue.Add(new MemberValue()
                    {
                        CodeValue = drv[Constants.MDSADMINISTRATION_CODE].ToString(),
                        MemberName = Constants.MDSADMINISTRATION_CODE,
                        ValueSource = drv[Constants.MDSADMINISTRATION_CODE].ToString(),
                        Attribute = BusinessHelper.getServerDirectionModel(sDirection, modelA, modelB).Entities[CompareEntity.getEntityKey(aem.EntityName)].Attributes[CompareAttribute.getAttributeKey(Constants.MDSADMINISTRATION_CODE, Constants.MEMBER_TYPE_LEAF)]
                    });

                    string destinationServerName = "";
                    string sourceServerName = "";
                    if (sDirection == ServerDirection.ServerB)
                    {
                        destinationServerName = Constants.MDSADMINISTRATION_SERVB;
                        sourceServerName = Constants.MDSADMINISTRATION_SERVA;
                    }

                    if (sDirection == ServerDirection.ServerA)
                    {
                        destinationServerName = Constants.MDSADMINISTRATION_SERVA;
                        sourceServerName = Constants.MDSADMINISTRATION_SERVB;
                    }

                    foreach (var selectedColumn in lSelectedColumns)
                    {

                        var m = new MemberValue()
                            {
                                CodeValue = drv[Constants.MDSADMINISTRATION_CODE].ToString(),
                                MemberName = selectedColumn.Name,
                                ValueDestination = BusinessHelper.SetMemberValue(selectedColumn, drv, destinationServerName),
                                ValueSource = BusinessHelper.SetMemberValue(selectedColumn, drv, sourceServerName),
                                dataType = selectedColumn.dataType,
                                Attribute = BusinessHelper.getServerDirectionModel(sDirection, modelA, modelB).Entities[CompareEntity.getEntityKey(aem.EntityName)].Attributes[CompareAttribute.getAttributeKey(selectedColumn.Name, Constants.MEMBER_TYPE_LEAF)]
                            };


                        am.lMemberValue.Add(m);
                    }

                    aem.LActionMembers.Add(am);

                }

            }
            db.LActionEntityMembers.Add(aem);
        }


        private Dictionary<String, Dictionary<String, EntityColumn>> dDataCompareMetaData = new Dictionary<string, Dictionary<string, EntityColumn>>();
        private DataSet dsDataCompare = new DataSet();

        private void CompareData()
        {
            DataCompareClearPanel();
            dgDataCompareEntities.ItemsSource = null;

            BuildDataCompare bdc = new BuildDataCompare();
            BuildDataCompare.dsDataCompare = dsDataCompare;
            BuildDataCompare.dDataCompareMetaData = dDataCompareMetaData;
            BuildDataCompare.cStates = cStates;

            BuildDataCompare.ServerA = this.ServerA;
            BuildDataCompare.ServerB = this.ServerB;
            BuildDataCompare.sDirection = this.sDirection;
            BuildDataCompare.OnlyEntityDetails = !cStates.CompareAutoPopulate;
            bdc.DoWork = true;
            bdc.ShowDialog();


            if (!(bdc.Error == null))
            {

                MessageBox.Show("Entity: " + BuildDataCompare.EntityName + " " + bdc.Error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                dgDataCompareEntities.ItemsSource = BuildDataCompare.EntityDetails.Values;

                if (dsDataCompare.Tables.Count > 0)
                {
                    SetDataTabelFilterCompareGrids(dsDataCompare.Tables[0]);
                }
            }
        }


        private void buildEntityCompare(EntityDataCompreDetails ed)
        {
            Logger.Message("buildEntityCompare - Start");

            try
            {
                if (dsDataCompare.Tables.Contains(ed.Name) == false && ed.Processed == true)
                {
                    MessageBox.Show("Error", "Error in Building Compare Data. Table name can not be found Entity: " + ed.Name, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (ed.Processed == false)
                {


                    BuildDataCompare.dsDataCompare = dsDataCompare;
                    BuildDataCompare.dDataCompareMetaData = dDataCompareMetaData;
                    BuildDataCompare.ServerA = this.ServerA;
                    BuildDataCompare.ServerB = this.ServerB;
                    BuildDataCompare.EntityDataCompreDetail = ed;

                    BuildDataCompare bdc = new BuildDataCompare();

                    bdc.ShowDialog();

                    if (!(bdc.Error == null))
                    {
                        MessageBox.Show("Entity: " + BuildDataCompare.EntityName + " " + bdc.Error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }

                DataCompareClearPanel();

                if (ed.Match)
                {
                    var dtFiltered = SetDataTabelFilterCompareGrids(dsDataCompare.Tables[ed.Name]);

                    dgDataCompHelper.ItemsSource = dtFiltered.DefaultView;

                    Logger.Message("buildEntityCompare - Data Complete");

                    int columnIndex = 0;

                    buildColumnCheckCode(dtFiltered, ref columnIndex);

                    Logger.Message("buildEntityCompare - Build Columns Start");
                    buildColumns(ed.Name, dtFiltered, columnIndex);
                    Logger.Message("buildEntityCompare - Build Columns Complete");
                    //Used to Group scroll
                    dgScroller.ItemsSource = dtFiltered.DefaultView;

                    dgDataCompareEntities.Items.Refresh();

                    //Used to expand the last column
                    gPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                    var re = new Grid();
                    Grid.SetColumn(re, columnIndex);
                    gPanel.Children.Add(re);
                }
                else
                {
                    MessageBox.Show("The entity attributes do not match.", "Mismatch", MessageBoxButton.OK,
                                    MessageBoxImage.Warning);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error in Building Compare Data.", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private DataTable SetDataTabelFilterCompareGrids(DataTable dt)
        {
            if (dt.Rows.Count > 0)
            {
                switch (((ComboBoxItem)cbxMDCViewType.SelectedValue).Content.ToString())
                {
                    case Constants.DATA_COMPARE_FILTER_ALL:
                        {
                            var query = from r in dt.AsEnumerable()
                                        select r;

                            if (query.Count() > 0)
                            {
                                return query.CopyToDataTable();
                            }

                        }
                        break;
                    case Constants.DATA_COMPARE_FILTER_SAME:
                        {
                            var query = from r in dt.AsEnumerable()
                                        where
                                            r.Field<string>(Constants.MDSADMINISTRATION_SERVA +
                                                            Constants.MDSADMINISTRATION_HASHCODE) ==
                                            r.Field<string>(Constants.MDSADMINISTRATION_SERVB +
                                                            Constants.MDSADMINISTRATION_HASHCODE)
                                        select r;
                            if (query.Count() > 0)
                            {
                                return query.CopyToDataTable();
                            }
                        }
                        break;
                    case Constants.DATA_COMPARE_FILTER_DIFFERENT:
                        {
                            var query = from r in dt.AsEnumerable()
                                        where
                                            r.Field<string>(Constants.MDSADMINISTRATION_SERVA +
                                                            Constants.MDSADMINISTRATION_HASHCODE) !=
                                            r.Field<string>(Constants.MDSADMINISTRATION_SERVB +
                                                            Constants.MDSADMINISTRATION_HASHCODE)
                                        select r;
                            if (query.Count() > 0)
                            {
                                return query.CopyToDataTable();
                            }
                        }
                        break;
                }

                return dt.Clone(); ;
            }
            else
            {
                return dt;
            }
        }

        private void DataCompareClearPanel()
        {
            gPanel.Children.Clear();
            gPanel.ColumnDefinitions.Clear();
        }

        private void buildColumns(string entityName, DataTable dt, int columnIndex)
        {
            foreach (var eColumn in dDataCompareMetaData[entityName])
            {
                gPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(120) });
                var cc = new ColumnCompare();
                cc.ColumnHeaderName = eColumn.Value.Name;

                if (eColumn.Value.Name == Constants.MDSADMINISTRATION_HASH || eColumn.Value.Name == Constants.MDSADMINISTRATION_CODE)
                {
                    cc.VisibilityCheckBox = Visibility.Hidden;
                }

                cc.DataType = MDSHelper.GetMDSDataType(dt.Columns[eColumn.Value.NameA].DataType.FullName);

                cc.IsDomainEntity = eColumn.Value.isDomainEntity;

                cc.ItemSource = from r in dt.AsEnumerable()
                                select
                                    new CompareData()
                                    {
                                        BrushNull = hPinkGrey,
                                        BrushDifferent = sbLavinder,
                                        BrushSame = sbLightGrey,
                                        Col1 = r.IsNull(eColumn.Value.NameA) ? null : r[eColumn.Value.NameA].ToString(),
                                        Col2 = r.IsNull(eColumn.Value.NameB) ? null : r[eColumn.Value.NameB].ToString()
                                    };

                Grid.SetColumn(cc, columnIndex);
                gPanel.Children.Add(cc);

                columnIndex++;
                gPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(5) });
                var s = new GridSplitter();
                s.Width = 5;
                s.HorizontalAlignment = HorizontalAlignment.Stretch;
                Grid.SetColumn(s, columnIndex);
                gPanel.Children.Add(s);
                columnIndex++;
            }
        }

        private void buildColumnCheckCode(DataTable dt, ref int columnIndex)
        {
            gPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(120) });
            var cc = new ColumnCodeCheck();

            cc.CheckedAllColumnHeaders += (sender, args) => SetGPanelColumnHeaderCheckBoxes(true);
            cc.UncheckedAllColumnHeaders += (sender, args) => SetGPanelColumnHeaderCheckBoxes(false);
            cc.ItemSource = dt.DefaultView;

            Grid.SetColumn(cc, columnIndex);
            gPanel.Children.Add(cc);

            columnIndex++;
            gPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(5) });
            var sc = new GridSplitter();
            sc.Width = 5;
            sc.HorizontalAlignment = HorizontalAlignment.Stretch;
            Grid.SetColumn(sc, columnIndex);
            gPanel.Children.Add(sc);
            columnIndex++;
        }

        private void SetGPanelColumnHeaderCheckBoxes(bool CheckBoxHeaderState)
        {
            foreach (var col in gPanel.Children)
            {
                if (col.GetType().FullName == Constants.MDSADMINISTRATION_COLUMNCOMPARE)
                {
                    if (((ColumnCompare)col).ColumnHeaderName != Constants.MDSADMINISTRATION_HASH && ((ColumnCompare)col).ColumnHeaderName != Constants.MDSADMINISTRATION_CODE)
                    {
                        ((ColumnCompare)col).checkBox.IsChecked = CheckBoxHeaderState;
                    }
                }
            }
        }

        #endregion

        private void btnModelCompareAtttributeSortOrder_Click(object sender, RoutedEventArgs e)
        {
            List<ComparedAttributes> cas = (List<ComparedAttributes>)dgDataAttributes.DataContext;

            SortOrder so = new SortOrder();

            if (sDirection == ServerDirection.ServerB)
            {
                so.Server = ServerA;

                var co = (ComparedObject)dgDataMdsObject.SelectedItem;
                if (modelA.Entities.ContainsKey(CompareEntity.getEntityKey(co.ObjectName)))
                {
                    so.Entity = modelA.Entities[CompareEntity.getEntityKey(co.ObjectName)];
                }
            }
            else
            {
                so.Server = ServerB;

                var co = (ComparedObject)dgDataMdsObject.SelectedItem;
                if (modelB.Entities.ContainsKey(CompareEntity.getEntityKey(co.ObjectName)))
                {
                    so.Entity = modelB.Entities[CompareEntity.getEntityKey(co.ObjectName)];
                }
            }

            so.ShowDialog();

            if (so.Deployed)
            {
                CompareModel();
            }

            selectEntity(so.Entity);
        }

        private void selectEntity(CompareEntity entity)
        {
            foreach (var item in dgDataMdsObject.Items)
            {
                ComparedObject co = (ComparedObject)item;
                if (co.ObjectName == entity.Name && co.ObjectType == Constants.OBJECT_TYPE_ENTITY)
                {
                    dgDataMdsObject.SelectedItem = item;
                    dgDataMdsObject.Focus();
                    break;
                }

            }

        }
        private void btnDataHelperDeploy_Click(object sender, RoutedEventArgs e)
        {
            DeploymentBuilder db = new DeploymentBuilder();
            db.CurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

            db.Server = getServer();

            if (dgDataMdsObject.Items.SourceCollection != null)
            {
                if (dgDataMdsObject.DataContext.GetType().FullName == "System.Windows.Data.ListCollectionView")
                {
                    List<ComparedObject> lCO = ((List<ComparedObject>)((ListCollectionView)dgDataMdsObject.DataContext).SourceCollection);
                    BusinessHelper.getSelectedEntities(db, modelA, modelB, sDirection, cStates, lCO);
                    BusinessHelper.getSelectedViews(db, modelA, modelB, sDirection, lCO);
                }
                
            }

            BusinessHelper.getSelectedAttributes(db, modelA, modelB, sDirection, cStates);
            BusinessHelper.getSelectedAttributeGroups(db, modelA, modelB, sDirection, cStates);
            BusinessHelper.getSelectedAttributeGroupDetails(db, modelA, modelB, sDirection, cStates);
            
            var dlg = new DeploymentWindow();
            dlg.db = db;
            dlg.ShowDialog();
        }
        private void btnModelCompareAtttributeDelete_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult r = MessageBox.Show("You are about to delete selected attributes. The selected attributes will be marked as deleted. All data will be lost in selected attributes. Press deploy to generate script.", "Warning", MessageBoxButton.OKCancel,
                            MessageBoxImage.Warning);

            if (r.HasFlag(MessageBoxResult.OK) == true)
            {
                var attributes = (List<ComparedAttributes>)dgDataAttributes.DataContext;
                foreach (var a in attributes)
                {
                    if (a.Checked)
                    {
                        a.Status = ObjectStatus.Delete;
                    }
                }

                dgDataAttributes.Items.Refresh();
            }
        }

        #region Menu
        private void mnuToolExport_Click(object sender, RoutedEventArgs e)
        {
            var em = new ExportModel();
            em.modelA = modelA;
            em.modelB = modelB;
            em.ShowDialog();
        }

        private void mnuToolExcelTemplateGen_Click(object sender, RoutedEventArgs e)
        {
            var excel = new ExcelTemplateGen();
            excel.modelA = modelA;
            excel.modelB = modelB;
            excel.ServerA = ServerA;
            excel.ServerB = ServerA;
            excel.ShowDialog();
        }



        private void mnuHelpAdd_Click(object sender, RoutedEventArgs e)
        {
            var a = new About();
            a.ShowDialog();
        }
        #endregion

        private void cbxMDCViewType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dgDataCompareEntities.SelectedItem != null && dgDataCompareEntities.SelectedIndex > 0)
            {
                var ed = (EntityDataCompreDetails)dgDataCompareEntities.SelectedItem;
                SelectionChangedEntityCompare(ed);
            }
        }



        private bool ModelsLoaded()
        {
            if (modelA == null || modelB == null)
                return false;
            return true;
        }

        #region Excel Upload
        private void dgExcelUploadSimSheet_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.Column.Header.ToString().Contains(Constants.EXCELUPLOAD_MDSADMIN) && cbxExcelUploadSimShowFlags.IsChecked == false)
            {
                e.Cancel = true;
            }
        }
        private void btnExcelUploadSimCheck_Click(object sender, RoutedEventArgs e)
        {
            using (new WaitCursor())
            {
                if (!ModelsLoaded())
                {
                    MessageBox.Show("No models loaded");
                    return;
                }

                SheetDetailLoad sheet = (SheetDetailLoad)cbxExcelUploadSimSheets.SelectedItem;

                sheet.ResetValidation();

                euSimple.ExcelSheetAnalysis(sheet,
                    cbxExcelUploadCheckCode.IsChecked,
                    cbxExcelUploadCheckName.IsChecked,
                    BusinessHelper.getServerDirectionModel(sDirection, modelA, modelB),
                    getServer());

                dgExcelUploadSimSheet.ItemsSource = null;
                if (sheet.Data != null)
                {
                    dgExcelUploadSimSheet.ItemsSource = sheet.Data.DefaultView;
                }

                if (!(sheet.IsValid))
                {
                    MessageBox.Show(sheet.Message(), "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else
                {
                    MessageBox.Show("Validation Check successful.", "Success", MessageBoxButton.OK);
                }
            }
        }

        private void btnExcelUploadAdvNext_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!ModelsLoaded())
                {
                    MessageBox.Show("No models loaded");
                    return;
                }
                if (String.IsNullOrEmpty(txtExcelUploadAdvFile.Text))
                {
                    MessageBox.Show("No File Selected");
                    return;
                }
                using (new WaitCursor())
                {
                    eua.NextState();
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show("Error has occured.", "Error", MessageBoxButton.OK,
                    MessageBoxImage.Error);
                Console.WriteLine("Message: " + Environment.NewLine + ex.Message);
                Console.WriteLine("InnerException: " + Environment.NewLine + ex.InnerException);
                Console.WriteLine("StackTrace: " + Environment.NewLine + ex.StackTrace);
            }
        }

        private void dgExcelUploadAdvTableMappings_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (e.AddedItems.Count > 0)
                {
                    var drv = (DataRowView)e.AddedItems[0];
                    eua.GetTableDetails(drv["ExcelTableName"].ToString());
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void cmExcelUploadAdvTableMappingsCreateTable_Click(object sender, RoutedEventArgs e)
        {
            var TableName = ((DataRowView)dgExcelUploadAdvTableMappings.SelectedItem)["ExcelTableName"].ToString();
            eua.CreateSqlTable(TableName);
        }

        private void btnExcelUploadAdvBack_Click(object sender, RoutedEventArgs e)
        {
            eua.BackState();
        }

        private void btnExcelUploadAdvCancel_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnExcelUploadAdvRefresh_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (new WaitCursor())
                {
                    eua.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        public void LoadDdgExcelUploadAdvLoadFiles(List<SheetDetailLoad> Sheets)
        {
            dgExcelUploadAdvLoadFiles.ItemsSource = null;
            dgExcelUploadAdvLoadFiles.ItemsSource = Sheets;
        }

        private void dgExcelUploadAdvLoadFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 &&
                e.AddedItems[0].GetType().FullName == Constants.SHEETDETAILSLOAD)
            {
                var Sheet = (SheetDetailLoad)e.AddedItems[0];

                if (Sheet.Data == null)
                {
                    try
                    {
                        using (new WaitCursor())
                        {
                            var result = eua.LoadSpreadSheet(Sheet, true, txtExcelUploadAdvFile.Text,
                                BusinessHelper.getServerDirectionModel(sDirection, modelA, modelB));
                            if (result == null)
                            {
                                dgExcelUploadAdvLoadFileData.ItemsSource = null;
                                if (!Sheet.IsValid)
                                {
                                    MessageBox.Show(Sheet.Message(), "Spreadsheet Tab Error", MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                                }
                            }
                            else
                            {
                                dgExcelUploadAdvLoadFileData.ItemsSource = result;
                            }

                        }
                    }
                    catch (SystemException ex)
                    {
                        MessageBox.Show("Error has occured while loading the excel file", "Error", MessageBoxButton.OK,
                            MessageBoxImage.Error);
                        Console.WriteLine("Message: " + Environment.NewLine + ex.Message);
                        Console.WriteLine("InnerException: " + Environment.NewLine + ex.InnerException);
                        Console.WriteLine("StackTrace: " + Environment.NewLine + ex.StackTrace);
                    }
                }
                else
                {
                    dgExcelUploadAdvLoadFileData.ItemsSource = Sheet.Data.DefaultView;
                }
            }
        }

        private void btnExcelUploadAdvOpen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!ModelsLoaded())
                {
                    MessageBox.Show("No models loaded");
                    return;
                }
                txtExcelUploadAdvFile.Text = eua.OpenExcelFile();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            dgExcelUploadAdvLoadFiles.ItemsSource = null;
            dgExcelUploadAdvLoadFiles.Items.Refresh();
            dgExcelUploadAdvLoadFileData.ItemsSource = null;
            dgExcelUploadAdvLoadFileData.Items.Refresh();

            if (eua.Sheets != null)
            {
                LoadDdgExcelUploadAdvLoadFiles(eua.Sheets);
            }
        }


        private void btnExcelUploadSimOpen_Click(object sender, RoutedEventArgs e)
        {   
            try
            {
                txtExcelUploadSimFile.Text = euSimple.OpenExcelFile();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            cbxExcelUploadSimSheets.ItemsSource = null;

            if (euSimple.Sheets != null)
            {
                cbxExcelUploadSimSheets.ItemsSource = euSimple.Sheets;
            }
        }

        private void cbxExcelUploadSimSheets_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            dgExcelUploadSimSheet.ItemsSource = null;
            if (e.AddedItems.Count > 0 && e.AddedItems[0].GetType().FullName == Constants.SHEETDETAILSLOAD)
            {
                var Sheet = (SheetDetailLoad)e.AddedItems[0];
                Sheet.ResetValidation();

                if (!ModelsLoaded())
                {
                    MessageBox.Show("No models loaded");
                    return;
                }

                try
                {
                    var result = euSimple.LoadSpreadSheet(Sheet, cbxExcelUploadTrim.IsChecked, txtExcelUploadSimFile.Text, BusinessHelper.getServerDirectionModel(sDirection, modelA, modelB));
                    if (!(Sheet.IsValid))
                    {
                        MessageBox.Show(Sheet.Message(), "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    dgExcelUploadSimSheet.ItemsSource = result;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error has occured", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine("Message: " + ex.Message);
                    Console.WriteLine("InnerException: " + ex.InnerException);
                    Console.WriteLine("StackTrace: " + ex.StackTrace);
                }

            }
        }

        private void btnExcelUploadSimPublish_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!ModelsLoaded())
                {
                    MessageBox.Show("No models loaded");
                    return;
                }
                var sheet = (SheetDetailLoad)cbxExcelUploadSimSheets.SelectedItem;

                euSimple.ExcelSheetAnalysis(sheet,
                    cbxExcelUploadCheckCode.IsChecked,
                    cbxExcelUploadCheckName.IsChecked,
                    BusinessHelper.getServerDirectionModel(sDirection, modelA, modelB),
                    getServer());

                dgExcelUploadSimSheet.ItemsSource = null;
                dgExcelUploadSimSheet.ItemsSource = sheet.Data.DefaultView;

                if (sheet.IsValid)
                {
                    DeploymentBuilder db = new DeploymentBuilder();
                    db.CurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                    db.Server = getServer();
                    euSimple.deployExcelSheet(sheet, db, BusinessHelper.getServerDirectionModel(sDirection, modelA, modelB), getServer());
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("An error has occured.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine("Error Message");
                Console.WriteLine(ex.Message);
                Console.WriteLine("InnerException");
                Console.WriteLine(ex.InnerException);

            }
        }

        private void btnExcelUploadSimrefresh_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (new WaitCursor())
                {
                    SheetDetailLoad currentSd = null;
                    if (cbxExcelUploadSimSheets.SelectedItem != null)
                    {
                        currentSd = ((SheetDetailLoad)(cbxExcelUploadSimSheets.SelectedItem));
                        currentSd.ResetValidation();
                    }

                    euSimple.GetExcelSheetNames();
                    cbxExcelUploadSimSheets.ItemsSource = null;

                    if (euSimple.Sheets != null)
                    {
                        cbxExcelUploadSimSheets.ItemsSource = euSimple.Sheets;
                        if (currentSd != null)
                        {
                            foreach (var s in euSimple.Sheets)
                            {
                                if (s.SheetName == currentSd.SheetName)
                                {
                                    cbxExcelUploadSimSheets.SelectedItem = s;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("An error has occured.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine("Error Message");
                Console.WriteLine(ex.Message);
                Console.WriteLine("InnerException");
                Console.WriteLine(ex.InnerException);

            }
        }


        #endregion

        private void dgDataAttributeGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 && e.AddedItems[0].GetType().FullName == Constants.MDSADMINISTRATION_COMPAREDATTRIBUTEGROUPS)
            {
                ClearAttributeGroupDetailsData();
                dgDataAttributeGroupDetails.DataContext = null;
                dgDataAttributeGroupDetailProperties.DataContext = null;
                var cag = (ComparedAttributeGroups)e.AddedItems[0];
                if (cag.comparedObject != null)
                {
                    switch (cag.comparedObject.locationType)
                    {
                        case ObjectStatus.ServerA:
                            {
                                dgDataAttributeGroupProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroupA(cag, modelA, modelB);
                                dgDataAttributeGroupDetails.DataContext = BusinessHelper.buildServerACompareAttributeGroupDetails(cag);
                                break;
                            }
                        case ObjectStatus.ServerB:
                            {
                                dgDataAttributeGroupProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroupB(cag, modelA, modelB);
                                dgDataAttributeGroupDetails.DataContext = BusinessHelper.buildServerBCompareAttributeGroupDetails(cag);
                                break;
                            }
                        case ObjectStatus.Same:
                        case ObjectStatus.Different:
                        case ObjectStatus.Rename:
                            {
                                if (cag.Status == ObjectStatus.Missing && cag.AttributeGroupA != null && !string.IsNullOrEmpty(cag.AttributeGroupA.Name))
                                {
                                    dgDataAttributeGroupProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroupA(cag, modelA, modelB);
                                    dgDataAttributeGroupDetails.DataContext = BusinessHelper.buildServerACompareAttributeGroupDetails(cag);
                                }
                                else if (cag.Status == ObjectStatus.Missing && cag.AttributeGroupB != null && !string.IsNullOrEmpty(cag.AttributeGroupB.Name))
                                {
                                    dgDataAttributeGroupProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroupB(cag, modelA, modelB);
                                    dgDataAttributeGroupDetails.DataContext = BusinessHelper.buildServerBCompareAttributeGroupDetails(cag);
                                }
                                else
                                {
                                    dgDataAttributeGroupProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroup(cag, modelA, modelB);
                                    dgDataAttributeGroupDetails.DataContext = BusinessHelper.buildServerSameDifferntRenameCompareAttributeGroupDetails(cag, cStates);
                                }
                                break;
                            }

                    }
                }
            }
        }

        private void dgDataAttributes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 && e.AddedItems[0].GetType().FullName == Constants.MDSADMINISTRATION_COMPAREDATTRIBUTES)
            {
                var ca = (ComparedAttributes)e.AddedItems[0];
                if (ca.comparedObject != null)
                {
                    switch (ca.comparedObject.locationType)
                    {
                        case ObjectStatus.ServerA:
                            {
                                dgDataAttribute.DataContext = BusinessHelper.PopulateComparedAttributeA(ca, modelA, modelB);
                                break;
                            }
                        case ObjectStatus.ServerB:
                            {
                                dgDataAttribute.DataContext = BusinessHelper.PopulateComparedAttributeB(ca, modelA, modelB);
                                break;
                            }
                        case ObjectStatus.Same:
                        case ObjectStatus.Different:
                            {
                                if ((ca.Status == ObjectStatus.Missing || ca.Status == ObjectStatus.Delete) && ca.AttributeA != null && !string.IsNullOrEmpty(ca.AttributeA.Name))
                                {
                                    dgDataAttribute.DataContext = BusinessHelper.PopulateComparedAttributeA(ca, modelA, modelB);
                                }
                                else if ((ca.Status == ObjectStatus.Missing || ca.Status == ObjectStatus.Delete) && ca.AttributeB != null && !string.IsNullOrEmpty(ca.AttributeB.Name))
                                {
                                    dgDataAttribute.DataContext = BusinessHelper.PopulateComparedAttributeB(ca, modelA, modelB);
                                }
                                else
                                {
                                    dgDataAttribute.DataContext = BusinessHelper.PopulateComparedAttribute(ca, modelA, modelB);
                                }
                                break;
                            }
                        case ObjectStatus.Rename:
                            {
                                dgDataAttribute.DataContext = BusinessHelper.PopulateComparedAttribute(ca, modelA, modelB);
                                break;
                            }

                    }
                }
            }
        }


        private void dgDataAttributeGroups_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            ComparedAttributeGroups RowDataContaxt = e.Row.DataContext as ComparedAttributeGroups;
            if (RowDataContaxt != null)
            {
                switch (RowDataContaxt.Status)
                {
                    case ObjectStatus.Delete:
                        {
                            e.Row.Background = lgbLightRedVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Missing:
                        {
                            e.Row.Background = lgbLightPurpleVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Different:
                        {
                            e.Row.Background = lgbLightGreenVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Rename:
                        {
                            e.Row.Background = lgbLightOrangeVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Same:
                        {
                            e.Row.Background = System.Windows.Media.Brushes.White;
                        }
                        break;
                }
            }
        }

        private void btnModelCompareAtttributeGroupSortOrder_Click(object sender, RoutedEventArgs e)
        {
            List<ComparedAttributeGroups> cas = (List<ComparedAttributeGroups>)dgDataAttributeGroups.DataContext;

            SortOrder so = new SortOrder();

            if (sDirection == ServerDirection.ServerB)
            {
                so.Server = ServerA;

                var co = (ComparedObject)dgDataMdsObject.SelectedItem;
                if (modelA.Entities.ContainsKey(CompareEntity.getEntityKey(co.ObjectName)))
                {
                    so.Entity = modelA.Entities[CompareEntity.getEntityKey(co.ObjectName)];
                }
            }
            else
            {
                so.Server = ServerB;

                var co = (ComparedObject)dgDataMdsObject.SelectedItem;
                if (modelB.Entities.ContainsKey(CompareEntity.getEntityKey(co.ObjectName)))
                {
                    so.Entity = modelB.Entities[CompareEntity.getEntityKey(co.ObjectName)];
                }
            }

            so.ShowDialog();

            if (so.Deployed)
            {
                CompareModel();
            }

            selectEntity(so.Entity);
        }

        private void btnModelCompareAtttributeGroupDelete_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult r = MessageBox.Show("You are about to delete selected attribute groups. The selected attribute groups will be marked as deleted. Press deploy to generate script.", "Warning", MessageBoxButton.OKCancel,
                           MessageBoxImage.Warning);

            if (r.HasFlag(MessageBoxResult.OK) == true)
            {
                var cags = (List<ComparedAttributeGroups>)dgDataAttributeGroups.DataContext;
                foreach (var cag in cags)
                {
                    if (cag.Checked)
                    {
                        cag.Status = ObjectStatus.Delete;
                    }
                }

                dgDataAttributeGroups.Items.Refresh();
            }
        }

        private void CompareObjectResultColour(object sender, DataGridRowEventArgs e)
        {
            ComparedObjectResult RowDataContaxt = e.Row.DataContext as ComparedObjectResult;
            if (RowDataContaxt != null && RowDataContaxt.A != null && RowDataContaxt.B != null)
            {

                if (!(RowDataContaxt.A.Equals(RowDataContaxt.B)))
                {
                    e.Row.Background = lgbLightGreenVerticalGradient;
                }
            }
        }
        private void dgDataAttributeGroupProperties_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            CompareObjectResultColour(sender, e);
        }

        private void dgDataAttributeGroupDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 && e.AddedItems[0].GetType().FullName == Constants.MDSADMINISTRATION_COMPAREDATTRIBUTEGROUPDETAILS)
            {
                var cagd = (ComparedAttributeGroupDetails)e.AddedItems[0];

                switch (cagd.Status)
                {
                    case ObjectStatus.ServerA:
                        {
                            dgDataAttributeGroupDetailProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroupDetailA(cagd);
                            break;
                        }
                    case ObjectStatus.ServerB:
                        {
                            dgDataAttributeGroupDetailProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroupDetailB(cagd);
                            break;
                        }
                    case ObjectStatus.Same:
                    case ObjectStatus.Different:
                        {
                            if (cagd.Status == ObjectStatus.Missing && cagd.AttributeGroupDetailA != null)
                            {
                                dgDataAttributeGroupDetailProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroupDetailA(cagd);
                            }
                            else if (cagd.Status == ObjectStatus.Missing && cagd.AttributeGroupDetailB != null)
                            {
                                dgDataAttributeGroupDetailProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroupDetailB(cagd);
                            }
                            else
                            {
                                dgDataAttributeGroupDetailProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroupDetail(cagd);
                            }
                            break;
                        }
                    case ObjectStatus.Rename:
                        {
                            dgDataAttributeGroupDetailProperties.DataContext = BusinessHelper.PopulateComparedAttributeGroupDetail(cagd);
                            break;
                        }

                }

            }
        }

        private void dgDataAttributeGroupDetails_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            ComparedAttributeGroupDetails RowDataContaxt = e.Row.DataContext as ComparedAttributeGroupDetails;
            if (RowDataContaxt != null)
            {
                switch (RowDataContaxt.Status)
                {
                    case ObjectStatus.Delete:
                        {
                            e.Row.Background = lgbLightRedVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Missing:
                        {
                            e.Row.Background = lgbLightPurpleVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Different:
                        {
                            e.Row.Background = lgbLightGreenVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Rename:
                        {
                            e.Row.Background = lgbLightOrangeVerticalGradient;
                        }
                        break;
                    case ObjectStatus.Same:
                        {
                            e.Row.Background = System.Windows.Media.Brushes.White;
                        }
                        break;
                }
            }
        }

        private void btnModelCompareAtttributeGroupDetailSortOrder_Click(object sender, RoutedEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void btnModelCompareAtttributeGroupDetailDelete_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult r = MessageBox.Show("You are about to delete selected attribute group details. The selected attribute group details will be marked as deleted. Press deploy to generate script.", "Warning", MessageBoxButton.OKCancel,
                           MessageBoxImage.Warning);

            if (r.HasFlag(MessageBoxResult.OK) == true)
            {
                var cagds = (List<ComparedAttributeGroupDetails>) dgDataAttributeGroupDetails.DataContext;
                foreach (var cagd in cagds)
                {
                    if (cagd.Checked)
                    {
                        cagd.Status = ObjectStatus.Delete;
                    }
                }

                dgDataAttributeGroupDetails.Items.Refresh();
            }
        }

        private void dgDataAttributeGroupDetailProperties_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            CompareObjectResultColour(sender, e);
        }

        private void btnExcelUploadAdvOpenMapping_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                txtExcelUploadAdvMappingFile.Text = ehMapper.OpenExcelFile();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            cbxExcelUploadAdvMappingSheets.ItemsSource = null;

            if (ehMapper.Sheets != null)
            {
                cbxExcelUploadAdvMappingSheets.ItemsSource = ehMapper.Sheets;
            }


        }

        private void btnExcelUploadAdvMappingLoad_Click(object sender, RoutedEventArgs e)
        {
            DataTable dt = ((DataView)dgExcelUploadAdvMapping.ItemsSource).Table;

            SqlConnectionStringBuilder scb = new SqlConnectionStringBuilder();
            scb.DataSource = getServer().ServerName;
            scb.InitialCatalog = txtExcelUploadAdvDatabaseName.Text;
            scb.IntegratedSecurity = true;
            scb.ConnectTimeout = 0;

            using (SqlConnection sqlConn = new SqlConnection(scb.ConnectionString))
            {
                try
                {
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn))
                    {
                        bulkCopy.DestinationTableName = "dbo.BKToMdmMapping";

                        foreach (DataColumn col in dt.Columns)
                        {
                            if (!col.ColumnName.Contains(Constants.EXCELUPLOAD_MDSADMIN))
                            {
                                bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(col.ColumnName, col.ColumnName));
                            }
                        }

                        bulkCopy.BatchSize = 1000;
                        // Write from the source to the destination.
                        sqlConn.Open();
                        bulkCopy.WriteToServer(dt);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        private void cbxExcelUploadAdvMappingSheets_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            dgExcelUploadAdvMapping.ItemsSource = null;
            if (e.AddedItems.Count > 0 && e.AddedItems[0].GetType().FullName == ExcelLoader.Constants.EXCELLOADER_SHEETDETAILS)
            {
                var Sheet = (SheetDetails)e.AddedItems[0];

                try
                {
                    var result = ehMapper.ReadExcelSheet(Sheet.SheetName, true);
                    dgExcelUploadAdvMapping.ItemsSource = result.DefaultView;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error has occured", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine("Message: " + ex.Message);
                    Console.WriteLine("InnerException: " + ex.InnerException);
                    Console.WriteLine("StackTrace: " + ex.StackTrace);
                }

            }
        }

        private void lbxExcelUploadAdvancedResults_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 && e.AddedItems[0].GetType().FullName == Constants.SYSTEM_DATA_DATATABLE)
            {
                dgExcelUploadAdvReportData.ItemsSource = ((DataTable)e.AddedItems[0]).DefaultView;
            }
        }

        private void btnExcelUploadAdvReportExport_Click(object sender, RoutedEventArgs e)
        {
            var sd = new SaveFileDialog();
            sd.Filter = "Excel|*.xlsx";

            if (sd.ShowDialog() == true)
            {
                using (new WaitCursor())
                {
                    FileInfo newFile = new FileInfo(sd.FileName);
                    if (newFile.Exists)
                    {
                        newFile.Delete(); // ensures we create a new workbook
                        newFile = new FileInfo(sd.FileName);
                    }

                    using (ExcelPackage package = new ExcelPackage(newFile))
                    {

                        foreach (var vdt in lbxExcelUploadAdvancedResults.Items)
                        {
                            DataTable dt = (DataTable)vdt;
                            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(dt.TableName);
                            ExcelHelper.PopulateSheet(worksheet, dt, true);
                        }

                        package.Save();
                    }
                }
                MessageBox.Show("Report Created.", "Complete", MessageBoxButton.OK);
            }
        }

        private void cbxExcelUploadAdvDataCheckValidate_Checked(object sender, RoutedEventArgs e)
        {
            BuildExecuteProcessString();
        }

        private void BuildExecuteProcessString()
        {
            if (cbxExcelUploadAdvDataCheckRegion != null && cbxExcelUploadAdvDataCheckRegion.SelectedValue != null)
            {
                txtExcelUploadAdvDataCheckExecute.Text =
                    BusinessHelper.BuildExecuteProcessString(cbxExcelUploadAdvDataCheckValidate.IsChecked,
                        cbxExcelUploadAdvDataCheckRegion.SelectedValue.ToString());
            }
        }

        private void cbxExcelUploadAdvDataCheckValidate_Unchecked(object sender, RoutedEventArgs e)
        {
            BuildExecuteProcessString();
        }

        private void cbxExcelUploadAdvDataCheckRegion_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            BuildExecuteProcessString();
        }

        private void btnExcelUploadAdvDataCheckExecute_Click(object sender, RoutedEventArgs e)
        {
            using (new WaitCursor())
            {
                lbxExcelUploadAdvancedDataCheck.ItemsSource = null;
                lbxExcelUploadAdvancedDataCheck.Items.Refresh();
                dgExcelUploadAdvDataCheck.ItemsSource = null;
                dgExcelUploadAdvDataCheck.Items.Refresh();

                DataSet ds = DataHelper.GetData(txtExcelUploadAdvDataCheckExecute.Text, getServer().ServerName,
                    txtExcelUploadAdvDatabaseName.Text);

                lbxExcelUploadAdvancedDataCheck.ItemsSource = ds.Tables;
                lbxExcelUploadAdvancedDataCheck.DisplayMemberPath = "TableName";
            }
        }

        private void lbxExcelUploadAdvancedDataCheck_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 && e.AddedItems[0].GetType().FullName == Constants.SYSTEM_DATA_DATATABLE)
            {
                dgExcelUploadAdvDataCheck.ItemsSource = ((DataTable)e.AddedItems[0]).DefaultView;
            }
        }

        private void btnExcelUploadSimExport_Click(object sender, RoutedEventArgs e)
        {
            var sd = new SaveFileDialog();
            sd.Filter = "Excel|*.xls;*.xlsx";

            if (sd.ShowDialog() == true)
            {
                using (new WaitCursor())
                {
                    FileInfo newFile = new FileInfo(sd.FileName);
                    if (newFile.Exists)
                    {
                        newFile.Delete(); // ensures we create a new workbook
                        newFile = new FileInfo(sd.FileName);
                    }

                    using (ExcelPackage package = new ExcelPackage(newFile))
                    {
                        SheetDetailLoad sheet = (SheetDetailLoad)cbxExcelUploadSimSheets.SelectedItem;

                        DataTable dt = sheet.Data;
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Result");
                        ExcelHelper.PopulateSheet(worksheet, dt, true);

                        package.Save();
                    }
                }
                MessageBox.Show("Report Created.", "Complete", MessageBoxButton.OK);
            }
        }

        private void cbxExcelUploadSimShowFlags_Checked(object sender, RoutedEventArgs e)
        {
            dgExcelUploadSimSheetRefresh();
        }

        private void dgExcelUploadSimSheetRefresh()
        {
            if (dgExcelUploadSimSheet.ItemsSource != null)
            {
                var data = dgExcelUploadSimSheet.ItemsSource;
                dgExcelUploadSimSheet.ItemsSource = null;
                dgExcelUploadSimSheet.ItemsSource = data;
            }
        }

        private void cbxExcelUploadSimShowFlags_Unchecked(object sender, RoutedEventArgs e)
        {
            dgExcelUploadSimSheetRefresh();
        }

        private void cbxdgExcelUploadAdvLoadFilesAll_Initialized(object sender, EventArgs e)
        {
            cbxdgExcelUploadAdvLoadFilesAll = (CheckBox) sender;
        }
        
        private void cbxDataAttributesAll_Initialized(object sender, EventArgs e)
        {
            cbxDataAttributesAll = (CheckBox)sender;
        }

        private void cbxDataAttributeGroupsAll_Initialized(object sender, EventArgs e)
        {
            cbxDataAttributeGroupsAll = (CheckBox)sender;
        }

        private void cbxDataAttributeGroupDetailsAll_Initialized(object sender, EventArgs e)
        {
            cbxDataAttributeGroupDetailsAll = (CheckBox)sender;
        }
    }
}

